package com.tianze.library.base;

import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.squareup.leakcanary.RefWatcher;
import com.tianze.library.listener.SingleClickListener;
import com.tianze.library.utils.KeyBoardUtils;
import com.tianze.library.view.SimpleDialog;
import com.tianze.library.view.UpdateDialog;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import icepick.Icepick;

/**
 * Created by kingtami.
 */
public abstract class BaseFragment extends Fragment {

    public static final String BUNDLE_KEY_ARGS = "BUNDLE_KEY_ARGS";
    /**
     * 选择图片的返回码
     */
    public final static int SELECT_IMAGE_RESULT_CODE = 200;
    protected ActionBar mActionBar;
    protected BaseActivity mActivity;

    protected View rootView;
    protected Unbinder mUnbinder;

    protected boolean isPrepared;
    // fragment不在ViewPager里的时候要手动设置可见
    protected boolean isVisible;
    private String mImagePath;

    protected abstract int getLayoutId();

    /**
     * init step 1
     */
    protected abstract void initData();

    /**
     * init step 2
     */
    protected abstract void initView();

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Icepick.saveInstanceState(this, outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Icepick.restoreInstanceState(this, savedInstanceState);
        mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        mActivity = (BaseActivity) getActivity();
        isVisible = true;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(getLayoutId(), container, false);
            mUnbinder = ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            isPrepared = true;
            if (isPrepared && isVisible) {
                onVisible();
            }
            try {
            /*
              * 获得当前屏幕亮度的模式
              * SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
              * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
              */
                screenMode = Settings.System.getInt(getActivity().getContentResolver(),
                                                    Settings.System.SCREEN_BRIGHTNESS_MODE
                );
                // 获得当前屏幕亮度值 0--255
                screenBrightness = Settings.System.getInt(getActivity().getContentResolver(),
                                                          Settings.System.SCREEN_BRIGHTNESS
                );
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = BaseApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        clean();
    }

    private void clean() {
        OkHttpUtils.getInstance().cancelTag(this);
        EventBus.getDefault().unregister(this);
        mUnbinder.unbind();
        rootView = null;
    }

    protected void onVisible() {
        if (null == rootView)
            return;
        if (null != rootView && !isPrepared)
            return;
        initData();
        initView();
        isPrepared = false;
    }

    protected void setCustomTitle(String title) {
        if (null == mActivity) {
            return;
        }
        mActivity.setCustomTitle(title);
    }

    protected void setCustomTitle(@StringRes int title) {
        setCustomTitle(getString(title));
    }

    protected void setToolbarTitle(String title) {
        if (null == mActivity) {
            return;
        }
        mActivity.setToolbarTitle(title);
    }

    protected void setToolbarTitle(int title) {
        setToolbarTitle(getString(title));
    }

    protected void setToolbarSubTitle(String title) {
        if (null == mActivity) {
            return;
        }
        mActivity.setToolbarSubTitle(title);
    }

    protected void setToolbarSubTitle(int title) {
        setToolbarSubTitle(getString(title));
    }

    protected void setLeftActionText(int resId) {
        setLeftActionText(getString(resId));
    }

    protected void setLeftActionText(String resId) {
        if (null == mActivity) {
            return;
        }
        mActivity.setLeftActionText(resId);
    }

    protected void setLeftActionResource(int resId) {
        if (null == mActivity) {
            return;
        }
        mActivity.setLeftActionResource(resId);
    }

    protected void setRightActionText(int resId) {
        setRightActionText(getString(resId));
    }

    protected void setRightActionText(String resId) {
        if (null == mActivity) {
            return;
        }
        mActivity.setRightActionText(resId);
    }

    protected void setRightActionResource(int resId) {
        if (null == mActivity) {
            return;
        }
        mActivity.setRightActionResource(resId);
    }

    protected void showRightAction() {
        if (null == mActivity) {
            return;
        }
        mActivity.showRightTextAction();
    }

    protected void showRightImageAction() {
        if (null == mActivity) {
            return;
        }
        mActivity.showRightImageAction();
    }

    protected void hideLeftAction() {
        if (null == mActivity) {
            return;
        }
        mActivity.hideLeftImageAction();
        mActivity.hideLeftTextAction();
    }

    protected void hideRightAction() {
        if (null == mActivity) {
            return;
        }
        mActivity.hideRightTextAction();
        mActivity.hideRightImageAction();
    }

    protected void setRightActionListener(SingleClickListener ocl) {
        if (null == mActivity) {
            return;
        }
        mActivity.setRightActionListener(ocl);
    }


    protected void showWaitingDialog() {
        if (null == mActivity) {
            return;
        }
        mActivity.showWaitingDialog();
    }

    protected void showWaitingDialog(String title) {
        if (null == mActivity) {
            return;
        }
        mActivity.showWaitingDialog(title);
    }

    protected void hideWaitingDialog() {
        if (null == mActivity) {
            return;
        }
        mActivity.hideWaitingDialog();
    }

    protected boolean isWaitingDialogShowing() {
        if (null == mActivity) {
            return true;
        }
        return mActivity.isWaitingDialogShowing();
    }

    protected void toast(String message) {
        if (null == mActivity) {
            return;
        }
        mActivity.toast(message);
    }

    protected void toast(int message) {
        if (null == mActivity) {
            return;
        }
        mActivity.toast(message);
    }

    protected void showWarnDialog(String title) {
        if (null == mActivity) {
            return;
        }
        mActivity.showWarnDialog(title);
    }

    protected void showConfirmDialog(String message, SimpleDialog.OnSimpleClickListener listener) {
        if (null == mActivity) {
            return;
        }
        mActivity.showConfirmDialog(message, listener);
    }

    protected void showUpdateDialog(String message, UpdateDialog.OnSimpleClickListener confirmListener, UpdateDialog.OnSimpleClickListener cancelListener) {
        if (null == mActivity) {
            return;
        }
        mActivity.showUpdateDialog(message, confirmListener, cancelListener);
    }

    protected void showCustomConfirmDialog(String message, String confirm, String cancel, SimpleDialog.OnSimpleClickListener confirmListener, SimpleDialog.OnSimpleClickListener cancelListener) {
        if (null == mActivity) {
            return;
        }
        mActivity
                .showCustomConfirmDialog(message, confirm, cancel, cancelListener, confirmListener);
    }

    public boolean onBackPressed() {
        return false;
    }

    protected void finish() {
        getActivity().finish();
    }

    protected void hideKeyboard() {
        KeyBoardUtils.hideKeyboard(getActivity());
    }

    /**
     * 当前屏幕亮度的模式
     */
    protected int screenMode;

    /**
     * 当前屏幕亮度值 0--255
     */
    protected int screenBrightness;

    /**
     * 设置当前屏幕亮度的模式
     * SCREEN_BRIGHTNESS_MODE_AUTOMATIC=1 为自动调节屏幕亮度
     * SCREEN_BRIGHTNESS_MODE_MANUAL=0 为手动调节屏幕亮度
     */
    protected void setScreenMode(int value) {
        Settings.System
                .putInt(getActivity().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE,
                        value
                );
    }

    /**
     * 设置当前屏幕亮度值 0--255，并使之生效
     */
    protected void setScreenBrightness(float value) {
        Window mWindow = getActivity().getWindow();
        WindowManager.LayoutParams mParams = mWindow.getAttributes();
        float f = value / 255.0F;
        mParams.screenBrightness = f;
        mWindow.setAttributes(mParams);

        // 保存设置的屏幕亮度值
        Settings.System
                .putInt(getActivity().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS,
                        (int) value
                );
    }

    @Override
    public void onResume() {
        super.onResume();
        // 设置屏幕亮度值为原来的
        setScreenBrightness(screenBrightness);
        // 设置当前屏幕亮度的模式 为原来的
        setScreenMode(screenMode);
    }
}
